/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

/*
 * Created on 10/07/2004
 *
 */

package au.com.lastweekend.jim.io.jpeg.read;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.io.jpeg.HuffmanTableDirectory;
import au.com.lastweekend.jim.io.jpeg.JpegProcessingException;
import au.com.lastweekend.jim.io.jpeg.JpegSegment;
import au.com.lastweekend.jim.io.metadata.Directory;

/**
 * Decode the DHT jpeg segment (See Annex B 2.4.2 of Jpeg Specification)
 * 
 * @version $Id: HuffmanTableSegmentReader.java,v 1.2 2005/06/09 11:15:34 ggardner Exp $
 * @author grant@lastweekend.com.au
 * 
 */
public class HuffmanTableSegmentReader implements JpegSegmentReader {

    private static final Logger LOG = Logger.getLogger(HuffmanTableSegmentReader.class);

    /*
     * @see au.com.lastweekend.jim.io.jpeg.JpegSegmentReader#extractDirectory(au.com.lastweekend.jim.io.jpeg.JpegSegment)
     */
    public Directory extractDirectory(JpegSegment segment) throws JpegProcessingException {

        HuffmanTableDirectory firstHuffmanDirectory = null;
        HuffmanTableDirectory previousHuffmanDirectory = null;
        int offset = 0;
        do {

            boolean isACTable = (segment.getHigh4Bits(offset) == 1);
            byte tableID = segment.getLow4Bits(offset);
            if (LOG.isDebugEnabled()) {
                LOG.debug("HUFF id=" + tableID + " isAC=" + isACTable + " at offset " + offset);
            }
            offset++;
            /*
             * This list is known as BITS in the JPEG spec, except of course index begins at zero. So huffmanValueCount[i] refers
             * to the number of codes of length i+1 (still don't understand why they called it BITS, so I'll use something
             * meaningful to me)
             */
            byte[] numberOfHuffmanCodesByLength = new byte[16];

            /*
             * This is equivalent to LASTK from the spec, which represents the total number of Huffman codes available. LASTK
             * actually contains an extra value because the syntax for describing procedures in the spec needs a way to indicate
             * that the end of the list (array) has been reached. We obviously don't need that in Java....
             */
            int totalNumberOfCodes = 0;

            for (int i = 0; i < 16; i++) {
                byte numberOfCodes = segment.get8Bits(offset++);
                totalNumberOfCodes += numberOfCodes;
                numberOfHuffmanCodesByLength[i] = numberOfCodes;
            }

            byte[][] huffmanValues = new byte[16][]; // This list is known as
            // HUFFVAL in the JPEG
            // spec (could there be
            // more than
            // 255?)
            for (int i = 0; i < 16; i++) {
                byte numberOfCodes = numberOfHuffmanCodesByLength[i];
                huffmanValues[i] = new byte[numberOfCodes];
                for (int j = 0; j < numberOfCodes; j++) {
                    huffmanValues[i][j] = segment.get8Bits(offset++);
                }
            }

            HuffmanTableDirectory thisDirectory = new HuffmanTableDirectory(previousHuffmanDirectory, isACTable, tableID,
                    huffmanValues, segment);

            if (firstHuffmanDirectory == null) {
                firstHuffmanDirectory = thisDirectory;

            } else {
                previousHuffmanDirectory.setLinkedDirectory(thisDirectory);
            }
            previousHuffmanDirectory = thisDirectory;
        } while (offset < segment.getSize());
        return firstHuffmanDirectory;

    }

}